package cn.itcast.interceptor;

import cn.itcast.pojo.Common;
import cn.itcast.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

//@Component
public class LoginInterceptor implements HandlerInterceptor {
    //@Autowired
    private JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取令牌
        String token = request.getHeader("token");
        //判断令牌是否为空
        if (token == null){
            response.setStatus(401);
            return false;
        }
        //解析令牌
        try {
            Map<String, Object> stringObjectMap = jwtUtils.parseToken(token);
            //将id放到共享区
            Common.set(stringObjectMap.get("id"));
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Common.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
